//
//  RankViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/28.
//  Copyright © 2020 吴欧. All rights reserved.
//

#import "RankViewController.h"
#import "HEGoodsDetailsFooterView.h"
#import "HEGoodsRecomView.h"
#import "HEProtocalViewController.h"
#import "HealthFamily-Bridging-Header.h"
#import "HEHealthRankCell.h"
#import "HEHealthRankModel.h"
#import "HEHealthDetailsViewController.h"

@import Charts;
@import SwiftCus;

@interface RankViewController () <ChartViewDelegate, BMKLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource, HEHealthRankCellDelegate>

@property (nonatomic, strong) LineChartView *chartView;
@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象
@property (nonatomic, strong) BMKLocation *courrentLoc;

@property (nonatomic, assign) CLLocationCoordinate2D courrentCoord;

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSourceArr;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) CGFloat newScore;
@property (nonatomic, strong) UILabel *rankLb;
@property (nonatomic, strong) UILabel *scoreLb;
@property (nonatomic, strong) UIView *cellWarp;
@property (nonatomic, strong) UIImageView *owrHeadView;

@property (nonatomic, strong) NSMutableArray *selfRankList;
@property (nonatomic, strong) NSMutableArray *xAixTitles;
@property (nonatomic, strong) NSMutableArray *yValues;

@end

@implementation RankViewController

- (NSMutableArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (NSMutableArray *)selfRankList {
    if (!_selfRankList) {
        _selfRankList = [NSMutableArray array];
    }
    return _selfRankList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
 
//    [self showEmpty];
//    HETest *test = [[HETest alloc] init];
    
    self.view.backgroundColor = CViewBgColor;
    _yValues = @[].mutableCopy;
    _xAixTitles = @[].mutableCopy;
    
    [self setupNav];

    [self initChart];
    [self initOwnerCell];
    [self setCustomTableView:self.tableView];
 
    
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_cellWarp.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(-0);
        make.bottom.equalTo(self.view).offset(-0);
    }];
    
    [self getCurrentLocal];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUserInfo) name:KNotificationUserInfoChange object:nil];
}

- (void)saveCorrdiate {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[NSNumber numberWithFloat:_courrentCoord.latitude] forKey:@"latitude"];
    [params setValue:[NSNumber numberWithFloat:_courrentCoord.longitude] forKey:@"longitude"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KsaveCorrdiate parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues: responseObject];
        self.newScore = response.data.floatValue;
        _scoreLb.text = [NSString stringWithFormat:@"%.2f", response.data.floatValue];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

// 单次定位
- (void)getCurrentLocal {
    [self.locationManager requestLocationWithReGeocode:NO withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
       if (location) {//得到定位信息，添加annotation
            
            if (location.location) {
                NSLog(@"LOC = %@",location.location);
                self.courrentCoord = location.location.coordinate;
                
                [self saveCorrdiate];
                [self loadData];
            }
//            if (location.rgcData) {
//                NSLog(@"rgc = %@",[location.rgcData description]);
//            }
//
//            if (location.rgcData.poiList) {
//                for (BMKLocationPoi * poi in location.rgcData.poiList) {
//                    NSLog(@"poi = %@, %@, %f, %@, %@", poi.name, poi.addr, poi.relaiability, poi.tags, poi.uid);
//                }
//            }
//
//            if (location.rgcData.poiRegion) {
//                NSLog(@"poiregion = %@, %@, %@", location.rgcData.poiRegion.name, location.rgcData.poiRegion.tags, location.rgcData.poiRegion.directionDesc);
//            }
        }
    }];
}

- (void)loadData {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[NSNumber numberWithFloat:_courrentCoord.latitude] forKey:@"latitude"];
    [params setValue:[NSNumber numberWithFloat:_courrentCoord.longitude] forKey:@"longitude"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KhealthRank parameters:params success:^(id  _Nonnull responseObject) {
        
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
            [self.selfRankList removeAllObjects];
        }

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        NSArray *rank = response.data[@"rank"];
        NSArray *selfArr = response.data[@"self"];

        [self.dataSourceArr addObjectsFromArray:[HEHealthRankModel mj_objectArrayWithKeyValuesArray: rank]];
        [self.selfRankList addObjectsFromArray:[HEHealthRankModel mj_objectArrayWithKeyValuesArray: [[selfArr reverseObjectEnumerator] allObjects]]];
        [self.tableView reloadData];
        
        for (int i = 0; i < self.dataSourceArr.count; i++) {
            HEHealthRankModel *model = self.dataSourceArr[i];
            if ([user.id isEqualToString:model.usid]) {
                self.rankLb.text = model.rank_nbr;
            } 
        }
        
        self.xAixTitles = @[].mutableCopy;
        self.yValues = @[].mutableCopy;
        for (int i = 0; i < self.selfRankList.count; i++) {
            HEHealthRankModel *model = self.selfRankList[i];
            NSString *xTitle = [NSDate timestampToDate:model.create_date formaterMode:NSDateFormaterModeMD];
            [self.xAixTitles addObject: xTitle];
            
            [self.yValues addObject:[NSString stringWithFormat:@"%.2f", model.health_value]];
        }

        [self setupXAixTitle];
        [self setData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (rank.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }
 
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)setupNav {
    // 设置导航栏按钮
    [self zx_setRightBtnWithImgName:@"help" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [WOAlert alertShowTitle:@"温馨提示" message:@"对老年人群健康相关生命质量、常见慢性疾病进行分析，构建以健康相关生命质量为评价指标的健康管理评分，按照周边老人人群进行健康评分排名，体现本人在周围人群中的健康排名情况。此榜是按照收集到个人的相关生命质量、常见慢性疾病进行统计分析，仅供参考。" cancelButtonTitle:@"确定" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
            
        }];
    }];
}

- (void)initOwnerCell {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    
    UIView *cellWarp = [UIView new];
    cellWarp.backgroundColor = KWhiteColor;
    [self.view addSubview:cellWarp];
    _cellWarp = cellWarp;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkHealthClick)];
    [cellWarp addGestureRecognizer:tap];
    
    [cellWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_chartView.mas_bottom).offset(1);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(-0);
        make.height.offset(70);
    }];
    
    UILabel *rankLb = [UILabel new];
    rankLb.font = DYFont(16);
    rankLb.text = @"0";
    [cellWarp addSubview:rankLb];
    _rankLb = rankLb;
    
    // 商品图片
    UIImageView *owrHeadView = [UIImageView new];
    [owrHeadView sd_setImageWithURL:[NSURL URLWithString:user.avatar] placeholderImage:IMAGE_NAMED(@"defualt_icon")];
    owrHeadView.contentMode = UIViewContentModeScaleAspectFill;
    [cellWarp addSubview:owrHeadView];
    owrHeadView.layer.cornerRadius = 25;
    owrHeadView.layer.masksToBounds = YES;
    _owrHeadView = owrHeadView;
    
    UILabel *owrNameLb = [UILabel new];
    owrNameLb.font = DYBlodFont(16);
    owrNameLb.text = @"自己";
    [cellWarp addSubview:owrNameLb];

    UIImageView *arrowView = [UIImageView new];
    arrowView.contentMode = UIViewContentModeScaleAspectFill;
    arrowView.image = IMAGE_NAMED(@"go_gray");
    [cellWarp addSubview:arrowView];
    
    UILabel *scoreLb = [UILabel new];
    scoreLb.font = DYBlodFont(18);
    scoreLb.text = @"0";
    scoreLb.textColor = CNavBgColor;
    [cellWarp addSubview:scoreLb];
    _scoreLb = scoreLb;
    
    [rankLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellWarp);
        make.left.equalTo(cellWarp).mas_offset(15);
        make.width.mas_offset(30);
    }];
    
    [owrHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellWarp);
        make.left.equalTo(rankLb.mas_right).mas_offset(15);
        make.width.mas_offset(50);
        make.height.mas_offset(50);
    }];
    
    [owrNameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellWarp);
        make.left.equalTo(owrHeadView.mas_right).mas_offset(15);
    }];
    
    [scoreLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellWarp);
        make.right.equalTo(arrowView.mas_left).mas_offset(-15);
    }];
    
    [scoreLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellWarp);
        make.right.equalTo(cellWarp).mas_offset(-15);
        make.width.mas_offset(8);
        make.height.mas_offset(12);
    }];
}

- (void)refreshUserInfo {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;

    [_owrHeadView sd_setImageWithURL:[NSURL URLWithString:user.avatar] placeholderImage:IMAGE_NAMED(@"defualt_icon")];
}

- (void)checkHealthClick {
    HEHealthDetailsViewController *vc = [HEHealthDetailsViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
 
- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            weakSelf.isFromHeadRefresh = YES;
            weakSelf.pageNum = 1;
            [weakSelf loadData];
        }];

//        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
//            weakSelf.isFromHeadRefresh = NO;
//            weakSelf.pageNum += 1;
//            [weakSelf loadData];
//        }];

        [_tableView registerClass:[HEHealthRankCell class] forCellReuseIdentifier: KHEHealthRankCell]; 
    }
    return _tableView;
}

- (void)initChart {
    _chartView = [[LineChartView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + 15, KScreenWidth, 250)];
    _chartView.backgroundColor = KWhiteColor;
    [self.view addSubview:_chartView];

    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(ZXNavBarHeight + 15);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(-0);
        make.height.offset(200);
    }];

    _chartView.userInteractionEnabled = YES;

    _chartView.delegate = self;
    _chartView.minOffset = 20; // 内边距

    _chartView.chartDescription.enabled = NO;
    _chartView.dragEnabled = YES;
    [_chartView setScaleEnabled:YES];
    _chartView.pinchZoomEnabled = YES;
    _chartView.drawGridBackgroundEnabled = NO;
    _chartView.legend.enabled = NO;
    _chartView.doubleTapToZoomEnabled = NO; //是否支持双击缩放
    //高亮点击
    _chartView.highlightPerTapEnabled = YES;
    //没有数据时显示
    _chartView.noDataText = @"没有数据";

    ChartYAxis *leftAxis = _chartView.leftAxis;
    [leftAxis removeAllLimitLines];
//    leftAxis.axisMaximum = 200.0;
    [leftAxis setXOffset:10];  // y轴水平偏移
    leftAxis.axisMinimum = 0;
//    leftAxis.gridLineDashLengths = @[@5.f, @5.f];
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.drawLimitLinesBehindDataEnabled = YES;
//    leftAxis.drawGridLinesEnabled = NO;//不绘制网格线
    leftAxis.gridColor = CLightGrayColor;
    _chartView.rightAxis.enabled = NO;
    leftAxis.granularityEnabled = YES;
//    leftAxis.labelFont = DYFont(14);


    //[_chartView.viewPortHandler setMaximumScaleY: 2.f];
    //[_chartView.viewPortHandler setMaximumScaleX: 2.f];

//    ChartMarkerImage *marker = [[ChartMarkerImage alloc] init];

    [self setupXAixTitle];

    _chartView.legend.form = ChartLegendFormLine;
    [_chartView animateWithXAxisDuration:2.5];



    ChartXAxis *xAxis = _chartView.xAxis;
//    xAxis.labelFont = DYFont(14);
//    xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽
    xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置，默认是显示在上面的
    xAxis.drawGridLinesEnabled = NO;//不绘制网格线
//    xAxis.labelCount = 7;// 网格线数量
    xAxis.labelTextColor = KBlackColor;//label文字颜色
    xAxis.granularity = 1;

    [self setData];
}

- (void)setupXAixTitle {

    ChartIndexAxisValueFormatter *format = [[ChartIndexAxisValueFormatter alloc] initWithValues: _xAixTitles];
    [_chartView.xAxis setValueFormatter:format];
  
    BalloonMarker *marker = [[BalloonMarker alloc]
                             initWithColor: CNavBgColor
                             font: DYFont(14)
                             textColor: UIColor.whiteColor
                             insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0)
                             xAxisValueFormatter: format
                             yPrefix:@"健康分："];
    marker.chartView = _chartView;
    marker.minimumSize = CGSizeMake(80.f, 40.f);
    _chartView.marker = marker;
}

- (void)setData
{
  
    NSMutableArray *dataSets = [NSMutableArray array];
  
    
    NSArray *values = _yValues;
    NSMutableArray *yVals = [NSMutableArray array];
    for (int i = 0; i < values.count; i++)
    {
        NSString *valStr = [NSString stringWithFormat:@"%@", values[i]];
        double val = [valStr doubleValue];
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:val];
        [yVals addObject:entry];
    }

    LineChartDataSet *dataSet = [[LineChartDataSet alloc] initWithEntries:yVals label: @"line1"];

    dataSet.lineWidth = 3.0f;//折线宽度
    [dataSet setColor:CNavBgColor]; //折线颜色
    dataSet.drawValuesEnabled = NO;//是否在拐点处显示数据
//        dataSet.valueColors = @[self.colorArray[i]];//折线拐点处显示数据的颜色
//        dataSet.drawSteppedEnabled = NO;//是否开启绘制阶梯样式的折线图
    dataSet.drawCirclesEnabled = YES;//是否绘制拐点
    dataSet.circleRadius = 5.0f;//拐点半径
    dataSet.axisDependency = AxisDependencyLeft;
    dataSet.drawCircleHoleEnabled = YES;//是否绘制中间的空心
    dataSet.circleHoleRadius = 3.0f;//空心的半径
    dataSet.circleHoleColor = KWhiteColor;//空心的颜色
    [dataSet setCircleColor:CNavBgColor];
    dataSet.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
    dataSet.highlightColor = CNavBgColor;
//    dataSet.valueFont = [UIFont systemFontOfSize:12];
    [dataSets addObject:dataSet];

    LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
    self.chartView.data = nil;
    self.chartView.data = data;
    [self.chartView animateWithXAxisDuration:0.3f];
}

// 连续定位
- (void)startlocation {
    //开启定位服务
    [self.locationManager startUpdatingLocation];
}

#pragma mark - 定位 BMKLocationManagerDelegate
/**
 @brief 当定位发生错误时，会调用代理的此方法
 @param manager 定位 BMKLocationManager 类
 @param error 返回的错误，参考 CLError
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didFailWithError:(NSError * _Nullable)error {
    NSLog(@"定位失败");
}

/**
 @brief 该方法为BMKLocationManager提供设备朝向的回调方法
 @param manager 提供该定位结果的BMKLocationManager类的实例
 @param heading 设备的朝向结果
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
    if (!heading) {
        return;
    }
    NSLog(@"用户方向更新");
}

/**
 @brief 连续定位回调函数
 @param manager 定位 BMKLocationManager 类
 @param location 定位结果，参考BMKLocation
 @param error 错误信息。
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateLocation:(BMKLocation *)location orError:(NSError *)error {
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    } 
    _courrentLoc = location;
}


#pragma mark - UITableViewDataSource
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEHealthRankCell *cell = [_tableView dequeueReusableCellWithIdentifier: KHEHealthRankCell];
    cell.model = self.dataSourceArr[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthRankModel *model = self.dataSourceArr[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: KHEHealthRankCell cacheByIndexPath:indexPath configuration:^(HEHealthRankCell *cell) {
        cell.model = model;
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthRankModel *model = self.dataSourceArr[indexPath.row];

}

#pragma mark - HEHealthRankCellDelegate
- (void)cellWithThumbupTap:(HEHealthRankModel *)model {
    NSString *th = model.okThumbup ? @"-1" : @"1";
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:Kthumbup parameters:@{@"thumbup" : th, @"to_usid" : model.usid} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues: responseObject];
        if (response.success) {
            self.isFromHeadRefresh = YES;
            self.pageNum = 1;
            [self loadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationUserInfoChange object:nil];
}

@end
